<?php
include "func.php";
$m = explode(";",$_GET['m']);
$mode = $m[0];
if($mode == "view")
{
if(!$m[1])
    {
        echo "Please select a user.";
        exit;
    }
    $uid = $m[1];
    $user = $api->query("user",$uid);
    $datef = str_replace(' ','&\nb\s\p;','F j, Y g:i:s A'); # Add &nbsp; so columns don't screw up
    $contact = $user["contact"];
    $topics = count($user["topics"]);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Ramble Forums: Viewing <?=$user["name"]?>'s Profile</title>
</head>
<body>
<div id="viewprof">
    <h1><?=$user["name"]?></h1><?if($user["title"]){?>
    <h3><?=$user["title"]?></h3>
    <?}?>
    <div class="avatar">
        <?if($ava = $user["avatar"]) echo "<img src=\"uploads/avatars/$ava\" />"?>
    </div>
    <table class="contact">
        <tr>
            <?=contacts($contact,0)?>
        </tr>
    </table>
    <span class="contact_hidden" id="c0"></span>
    <h2>Info</h2>
    <table id="info" class="uinfo">
        <tr>
            <td>Topics:&nbsp;<?=$topics?></td>
            <td>Joined:&nbsp;<?=date($datef,$user["regdate"])?></td>
        </tr>
        <tr>
            <td>Posts:&nbsp;<?=$user["posts"]?></td>
            <td>Last Login:&nbsp;<?=date($datef,$user["lastlogin"])?></td>
        </tr>
    </table>
    <?if($user["topics"]){?>
    <h2>Recent Topics</h2>
    <table id="rectop" class="uinfo">
    <?php
        $i = 1;
        foreach(array_slice($user["topics"],-3) as $tid)
        {
            $topic = $api->query('topic',$tid);
    ?>
        <tr>
            <td>
                <a href="topic/view/<?=$tid?>"><?=$topic['title']?></a> <a onclick="tprev(<?=$i?>);" id="tpa<?=$i?>">v</a>
                <div id="tprev<?=$i?>" class="tprev"><?=trunc(strip_tags($topic['body'],"<b><i><u><br>"),50)?></div>
            </td>
        </tr>
    <?php
            $i++;
        }
    ?>
    </table>
    <?}?>
</div>
</body>
</html>
<?php
}
elseif($mode == "edit")
{
    if($m[1] == "profile")
    {
        $uid = $m[2];
        if(rank() < 3 and $uid != $_COOKIE['ramble_id'])
        {
            echo "You don't have the authority to do that.";
            exit;
        }
        $user = $api->query("user",$uid);
        if($m[3] == "submit")
        {
            $contacts = array("email","aim","msn","yahoo","gtalk","skype");
            $chngs = array();
            $delava = ($_POST['delava'] === "on");
            unset($_POST['delava'],$_POST['avatar']);
            $columns = array("title","email","aim","msn","skype","gtalk","signature");
            $params = array();
            foreach($columns as $k)
            {
                $v = $_POST[$k];
                if($v === "") $v = null;
                if($k != "signature" && $k != "title") $v = preg_replace('/[^a-zA-Z0-9@\.\-\[\]]/','',$v);
                else $v = mysql_escape_string($v);
                if($k == "signature") $chng = ($user['raw'] != $v);
                else $chng = (in_array($k,$contacts)) ? ($v != $user['contact'][$k]) : ($v != $user[$k]);
                if($chng)
                {
                    $chngs[] = 'user_'. $k .' = ?';
                    if($k != "avatar") $params[] = $v;
                }
            }
            $avatar = $_FILES["avatar"];
            if($delava)
            {
                if(unlink('uploads/avatars/'.$user['avatar']))
                {
                    if(!$avatar) $chngs[] = "user_avatar = ''";
                    $avchng = true;
                }
            }
            if($avatar)
            {
                $fname = explode('.',$avatar["name"]);
                $ext = $fname[(count($fname)-1)]; unset($fname[(count($fname)-1)]);
                $file = "$uid.$ext";
                $loc = "uploads/avatars/$file";
                list($aw,$ah) = array_slice(getimagesize($avatar["tmp_name"]),0,2);
                if($aw > 64 or $ah > 64) echo "Maximum avatar dimensions are 64 by 64 pixels.<br />";
                elseif(move_uploaded_file($avatar["tmp_name"], $loc))
                {
                    $chngs[] = "user_avatar = ?";
                    $params[] = $file;
                    $avchng = true;
                    echo true; # To make sure $avchng is set. TODO: Find a fix without having to do this
                }
            }
            if($chngs)
            {
                $sql = 'UPDATE '. $config['mysql']['prefix'] .'users SET ';
                $sql .= implode(", ",$chngs);
                $sql .= ' WHERE user_id='.$uid;
                $api->q($sql,$params);
                if($avchng) echo '<script>$("#userbox").lp("index.php?m=ubox", true); $("#content").lp("user.php?m=edit;profile;'.$uid.'");</script>';
                else echo "Profile updated.";
                exit;
            }
            else
            {
                echo "You didn't change anything.";
                exit;
            }
        }
        $user = $api->query("user",$uid);
        if($_COOKIE['PHPSESSID']) session_id($_COOKIE['PHPSESSID']);
        session_start();
        $_SESSION['KCl'] = shaker(32);
        $_SESSION['KCN'] = md5($_SESSION['KCl'] . $_COOKIE['PHPSESSID']);
        $url = "user.php?m=edit;profile;$uid;submit&amp;".SID;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Ramble Forums: Editing Profile</title>
</head>
<body>
<div id="res"></div>
<h1 class="edit">Edit Profile</h1>
<form id="prof" action="<?=$url?>" method="post" onsubmit="$('#prof').ajaxSubmit({beforeSubmit: function() {$('#res').fadeOut('fast');}, target: '#res', success: function() {$('#res').fadeIn(1000); pload();}}); return false;">
<table class="edit">
    <tr>
        <th>Title</th>
        <td colspan="2"><input type="text" value="<?=$user["title"]?>" name="title" /></td>
    </tr>
    <tr>
        <th>EMail</th>
        <td colspan="2"><input type="text" value="<?=$user["contact"]["email"]?>" name="email" /></td>
    </tr>
    <tr>
        <th>AIM</th>
        <td colspan="2"><input type="text" value="<?=$user["contact"]["aim"]?>" name="aim" /></td>
    </tr>
    <tr>
        <th>MSN</th>
        <td colspan="2"><input type="text" value="<?=$user["contact"]["msn"]?>" name="msn" /></td>
    </tr>
    <tr>
        <th>Skype</th>
        <td colspan="2"><input type="text" value="<?=$user["contact"]["skype"]?>" name="skype" /></td>
    </tr>
    <tr>
        <th>Google Talk</th>
        <td colspan="2"><input type="text" value="<?=$user["contact"]["gtalk"]?>" name="gtalk" /></td>
    </tr>
    <tr>
        <th>Signature</th>
        <td colspan="2"><textarea name="signature"><?=$user["raw"]?></textarea></td>
    </tr>
    <tr>
        <th>Avatar</th>
        <td colspan="2"><input type="file" name="avatar" /></td>
    </tr>
    <?if($user["avatar"]){?>
    <tr>
        <th>Current Avatar</th>
        <td><img src="uploads/avatars/<?=$user["avatar"]?>" /></td>
        <td>Delete? <input type="checkbox" name="delava" /></td>
    </tr>
    <?}?>
    <tr>
        <td colspan="3"><input type="submit" class="button" value="Update Profile" /></td>
    </tr>
</table>
</body>
</html>
<?php
    }
    elseif($m[1] == "preferences")
    {
        $uid = $m[2];
        if($uid != $_COOKIE['ramble_id'])
        {
            echo "You can't do that.";
            exit;
        }
        $prefs = $api->get("user","preferences",$uid);
        if($m[3] == "submit")
        {
            $fprefs = array();
            $nums = array("topic_sidelinks" => 5,"forum_sidelinks" => 5);
            if($_POST == $prefs)
            {
                echo "You didn't change anything.";
                exit;
            }
            foreach(array_keys($prefs) as $k)
            {
                $v = $_POST[$k];
                if(array_key_exists($k,$nums) and !preg_match("/^(\d+)$/",$v)) $fprefs[] = "$k:\"{$prefs[$k]}\"";
                elseif(intval($v) > $nums[$k]) $fprefs[] = "$k:\"{$nums[$k]}\"";
                else $fprefs[] = "$k:\"$v\"";
            }
            $nprefs = implode(",",$fprefs);
            $sql = 'UPDATE '. $config['mysql']['prefix'] .'users SET user_preferences=? WHERE user_id='. $uid;
            $api->q($sql,$nprefs);
            echo "Preferences updated.";
            exit;
        }
        if($_COOKIE['PHPSESSID']) session_id($_COOKIE['PHPSESSID']);
        session_start();
        $_SESSION['KCl'] = shaker(32);
        $_SESSION['KOH'] = md5($_SESSION['KCl'] . $_COOKIE['PHPSESSID']);
        $url = "user.php?m=edit;preferences;$uid;submit&amp;".SID;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <title>Ramble Forums: Editing Preferences</title>
</head>
<body>
<div id="res"></div>
<h1 class="edit">Edit Preferences</h1>
<form id="prof" action="<?=$url?>" method="post" onsubmit="$('#prof').ajaxSubmit({beforeSubmit: function() {$('#res').fadeOut('fast');}, target: '#res', success: function() {$('#res').fadeIn(1000); pload();}}); return false;">
<table class="edit">
<?php
        foreach($prefs as $k => $v)
        {
?>
    <tr>
        <th><?=$i18n->get("editing/prefs/$k")?></th>
        <td><input type="text" value="<?=$v?>" name="<?=$k?>" /></td>
    </tr>
<?php
        }
?>
    <tr>
        <td colspan="2"><input type="submit" class="button" value="Update Profile" /></td>
    </tr>
</table>
</body>
</html>
<?php
    }
}
?>